package com.jwdf.uda.ui.activity.presenter;

import android.content.Context;
import android.text.TextUtils;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.event.ConcernStatusEvent;
import com.jwdf.uda.event.NewProblemsEvent;
import com.jwdf.uda.event.QuizDetailEvent;
import com.jwdf.uda.event.QuizDetailItemClickEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.QuizAddVoteAction;
import com.jwdf.uda.http.action.QuizConcernAction;
import com.jwdf.uda.http.action.QuizDelAction;
import com.jwdf.uda.http.action.QuizDetailAction;
import com.jwdf.uda.http.action.QuizReplyListAction;
import com.jwdf.uda.http.action.QuizVoteInfoAction;
import com.jwdf.uda.http.action.ReplyDetailAction;
import com.jwdf.uda.ui.activity.EditAnswerActivity;
import com.jwdf.uda.ui.activity.NewAnswerActivity;
import com.jwdf.uda.ui.activity.QuizDetailActivity;
import com.jwdf.uda.ui.activity.VoteOptionListActivity;
import com.jwdf.uda.ui.activity.view.IQuizDetailView;
import com.jwdf.uda.ui.adapter.item.QuizDetailItem;
import com.jwdf.uda.utils.ConfigUtils;
import com.jwdf.uda.utils.EventBusUtil;
import com.jwdf.uda.utils.ShareUtil;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/5.
 */
public class QuizDetailPresenter extends APresenter<IQuizDetailView> {
    public PbBean.PbResQuestionFindQuestion mDetail;
    private int mQuizId;

    public QuizDetailPresenter(IQuizDetailView iView, int quizId) {
        super(iView);
        mQuizId = quizId;
    }

    public void doVoteAction(PbBean.PbSignBaseVoteOptionType optionId) {
        mIView.getFragment().showProgressDialog();
        QuizAddVoteAction action = QuizAddVoteAction.newInstance(mIView.getFragment().getActivity(), mQuizId, optionId);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionAddVote>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionAddVote> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
                    mIView.getFragment().closeProgressDialog();
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    doVoteSuccess(response.body());
                }
            }
        }));
    }

    private void doVoteSuccess(PbBean.PbResQuestionAddVote body) {
        getVoteListAction(0);
    }

    public void getVoteListAction(final int offset) {
//        if (offset == 0) {
//            mIView.getFragment().showProgressDialog();
//        }
        QuizVoteInfoAction action = QuizVoteInfoAction.newInstance(mIView.getFragment().getActivity(), mQuizId, offset);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionVoteInfo>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionVoteInfo> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
//                    if(offset==0) {
//                        mIView.getFragment().closeProgressDialog();
//                    }
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    doLoadVoteListSuccess(offset, response.body());
                }
            }
        }));
    }

    private void doLoadVoteListSuccess(int offset, PbBean.PbResQuestionVoteInfo votes) {
        if (offset > 0) {
            mIView.loadMoreVotes(votes.getVoterInfoList());
        } else {
            mIView.refreshVotes(votes);
        }
        mIView.setPullLoadEnable(votes.getVoterInfoCount() == ((QuizDetailActivity.QuizDetailFragment) mIView.getFragment()).getPageLength());
        //        EventBusUtil.post(VoteTabCountEvent.newInstanceForVote(mQuizId, votes.getVoterInfoCount()));
    }

    public void toAddReplyActivity(Context context, int voteCount) {
        NewAnswerActivity.start(context, mDetail.getQuestionInfo().getQuestionId(), voteCount, mDetail.getQuestionInfo().getTitle());
    }

    public void userEditReply(int replyId, final int voteCount) {
        mIView.getFragment().showProgressDialog();
        ReplyDetailAction action = ReplyDetailAction.newInstance(mIView.getFragment().getActivity(), replyId);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionFindAnswer>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionFindAnswer> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
                    mIView.getFragment().closeProgressDialog();
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    final PbBean.PbResQuestionFindAnswer body = response.body();
                    toEditReplyActivity(body, voteCount);
                }
            }
        }));
    }

    private void toEditReplyActivity(PbBean.PbResQuestionFindAnswer body, int voteCount) {
        if (body == null)
            return;
        EditAnswerActivity.start(mIView.getFragment().getActivity(), body, voteCount);
    }

    public void doDelQuizAction() {
//        mIView.getFragment().showProgressDialog();
        QuizDelAction action = QuizDelAction.newInstance(mIView.getFragment().getActivity(), mQuizId);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionDelQuestion>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionDelQuestion> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
//                    mIView.getFragment().closeProgressDialog();
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    mIView.getFragment().getActivity().finish();
                    //刷新列表
                    EventBusUtil.post(new NewProblemsEvent(NewProblemsEvent.EVENT_COMMENT_DELETE));
                }
            }
        }));
    }

    public void getReplyListAction(final int offset, final PbBean.PbSignBaseAnswerSort sort) {
//        if (offset == 0) {
//            mIView.getFragment().showProgressDialog();
//        }
        QuizReplyListAction action = QuizReplyListAction.newInstance(mIView.getFragment().getActivity(), mQuizId, offset, sort);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionAnswerList>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionAnswerList> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
//                    mIView.getFragment().closeProgressDialog();
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    doLoadReplyListSuccess(sort, offset, response.body());
                }
            }
        }));
    }

    private void doLoadReplyListSuccess(PbBean.PbSignBaseAnswerSort sort, int offset, PbBean.PbResQuestionAnswerList comments) {
        if (offset > 0) {
            mIView.loadMoreComments(comments.getAnswerListList());
        } else {
            mIView.refreshComments(comments.getAnswerListList(), comments.getRowCount());
            //            EventBusUtil.post(VoteTabCountEvent.newInstanceForComment(mQuizId, comments.getRowCount()));
            String sortType = "按热度排序";
            if (PbBean.PbSignBaseAnswerSort.ANSWER_SORT_BY_LIKE_DESC == sort) {
                sortType = "按热度排序";
            } else if (PbBean.PbSignBaseAnswerSort.ANSWER_SORT_BY_TIME_DESC == sort) {
                sortType = "按时间排序";
            }
            EventBusUtil.post(new QuizDetailEvent(QuizDetailEvent.EVENT_DO_SORT, sortType));
        }
        mIView.setPullLoadEnable(comments.getAnswerListCount() == ((QuizDetailActivity.QuizDetailFragment) mIView.getFragment()).getPageLength());
    }

    private void doLoadReplyListSuccess(int offset, PbBean.PbResQuestionAnswerList comments) {
        if (offset > 0) {
            mIView.loadMoreComments(comments.getAnswerListList());
        } else {
            mIView.refreshComments(comments.getAnswerListList(), comments.getRowCount());
            //            EventBusUtil.post(VoteTabCountEvent.newInstanceForComment(mQuizId, comments.getRowCount()));
        }
        mIView.setPullLoadEnable(comments.getAnswerListCount() == ((QuizDetailActivity.QuizDetailFragment) mIView.getFragment()).getPageLength());
    }

    public void doShareAction(Context context) {
//        if (mDetail != null && !TextUtils.isEmpty(mDetail.getQuestionInfo().getShareUrl())) {
        String title="【问题】"+mDetail.getQuestionInfo().getTitle();
        if(mDetail.getQuestionInfo().getConcernCount()>0){
            title=title+"-"+mDetail.getQuestionInfo().getConcernCount()+"人关注";
        }
        if(mDetail.getQuestionInfo().getAnswerCount()>0){
            title=title+","+mDetail.getQuestionInfo().getAnswerCount()+"人回答";
        }
        ShareUtil.onekeyShare(context, mDetail.getQuestionInfo().getQuickDescription(), mDetail.getQuestionInfo().getShareUrl(),title);
//        }
    }

    public void onEventMainThread(QuizDetailEvent event) {
        switch (event.getEvent()) {
            case QuizDetailEvent.EVENT_ADD_CONCERN:
            case QuizDetailEvent.EVENT_CANCEL_CONCERN:
                doConcernAction(event);
                break;
            case QuizDetailEvent.EVENT_TAB_REPLY:
                mIView.setCurrentTab(QuizDetailItem.QuizTab.REPLY);
                mIView.setPullLoadEnable(mIView.getCommentOffset() == ((QuizDetailActivity.QuizDetailFragment) mIView.getFragment()).getPageLength());
                break;
            case QuizDetailEvent.EVENT_TAB_VOTE:
//                if (canViewVoteResult()) {
//                    getVoteListAction(0);
//                } else {
//                    mIView.showUserTakeVote(mDetail.getQuestionInfo().getVoteOptionList().size());
//                }
                mIView.setCurrentTab(QuizDetailItem.QuizTab.VOTE);
                mIView.setPullLoadEnable(mIView.getVoteOffset() == ((QuizDetailActivity.QuizDetailFragment) mIView.getFragment()).getPageLength());
                break;
            case QuizDetailEvent.EVENT_REFRESH_VOTE:
                if (canViewVoteResult()) {
                    getVoteListAction(0);
                } else {
                    mIView.showUserTakeVote(mDetail.getQuestionInfo().getVoteOptionList().size());
                }
                break;
            case QuizDetailEvent.EVENT_SHOW_DROP_MENU:
//                mIView.setCurrentTab(QuizDetailItem.QuizTab.REPLY);
                mIView.showTabSortMenu(event.anchor);
                break;
            case QuizDetailEvent.EVENT_USER_TAKE_VOTE:
                mIView.showVoteConfirmDialog(event.optionId);
                break;
            case QuizDetailEvent.EVENT_USER_RE_TAKE_VOTE:
                mIView.showReVoteConfirmDialog(event.reOptionId);
                break;
        }
    }

    private boolean canViewVoteResult() {
        if (mDetail == null)
            return false;
        return (mDetail.getIsVote() == 1) || (TextUtils.equals(mDetail.getQuestionInfo().getUserInfo().getUserId(), ConfigUtils.getUserId(getContext())));
    }

    public void doConcernAction(final QuizDetailEvent event) {
//        mIView.getFragment().showProgressDialog();
        QuizConcernAction action = QuizConcernAction.newInstance(mIView.getFragment().getActivity(), mQuizId);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionAddConcern>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionAddConcern> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
//                    mIView.getFragment().closeProgressDialog();
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    doConcernSuccess(event);
                }
            }
        }));
    }

    private void doConcernSuccess(QuizDetailEvent e) {
        ConcernStatusEvent event = new ConcernStatusEvent();
        event.isConcern = QuizDetailEvent.EVENT_ADD_CONCERN == e.getEvent();
        event.concernCount = QuizDetailEvent.EVENT_ADD_CONCERN == e.getEvent() ? e.count + 1 : e.count - 1;
        EventBusUtil.post(event);
    }

    public void requestDetail() {
        if (mIView.getAdapterCount() == 0) {
            mIView.getFragment().showProgressDialog();
        }
        QuizDetailAction action = QuizDetailAction.newInstance(mIView.getFragment().getActivity(), mQuizId);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionFindQuestion>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionFindQuestion> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
                    mIView.getFragment().closeProgressDialog();
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    doSuccessResponse(response.body());
                }
            }
        }));
    }

    private void doSuccessResponse(PbBean.PbResQuestionFindQuestion body) {
        this.mDetail = body;
        if (mDetail == null)
            return;
        if (canViewVoteResult()) {
            getVoteListAction(0);
        } else {
            mIView.showUserTakeVote(mDetail.getQuestionInfo().getVoteOptionList().size());
        }
        mIView.showDetailData(mDetail);


        if (mIView.getCurrentTab() == QuizDetailItem.QuizTab.REPLY) {
            mIView.setPullLoadEnable(mDetail.getAnswerInfoList().size() == ((QuizDetailActivity.QuizDetailFragment) mIView.getFragment()).getPageLength());
            mIView.setCurrentTab(QuizDetailItem.QuizTab.REPLY);
        } else {
//            if (canViewVoteResult()) {
//                getVoteListAction(0);
//            } else {
//                mIView.showUserTakeVote(mDetail.getQuestionInfo().getVoteOptionList().size());
//            }
            mIView.setPullLoadEnable(mIView.getVoteOffset() == ((QuizDetailActivity.QuizDetailFragment) mIView.getFragment()).getPageLength());
            mIView.setCurrentTab(QuizDetailItem.QuizTab.VOTE);
        }
        mIView.showBottomView(body.getAnswerId(), body.getQuestionInfo().getVoteOptionList().size());
    }

    public void getReplyListAction(final int offset) {
        if (offset == 0) {
            mIView.getFragment().showProgressDialog();
        }
        QuizReplyListAction action = QuizReplyListAction.newInstance(mIView.getFragment().getActivity(), mQuizId, offset);
        mIView.getFragment().onNewRequestCall(action.request(new AHttpService.IResCallback<PbBean.PbResQuestionAnswerList>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResQuestionAnswerList> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (mIView.getFragment().getView() != null) {
                    mIView.getFragment().closeProgressDialog();
                    if (HttpHelper.showError(mIView.getFragment().getActivity(), resultCode, baseServerInfo, R.string.error_operation)) {
                        return;
                    }
                    doLoadReplyListSuccess(offset, response.body());
                }
            }
        }));
    }

    public void onEventMainThread(QuizDetailItemClickEvent event) {
        QuizDetailItem item = event.getItem();
        switch (item.itemType) {
            case QuizDetailItem.TYPE_VOTE_TITLE:
                if (item.planVoteCount > 0) {
                    //查看投票情况
                    toVoteOptionListActivity(item.optionId.getNumber());
                }
                break;
        }
    }

    public void toVoteOptionListActivity(int optionId) {
        VoteOptionListActivity.startActivity(mIView.getFragment().getActivity(), mQuizId, optionId);
    }

}
